<?php
/**
 * Created by PhpStorm.
 * User: Steven
 * Date: 2017/6/8
 */

namespace app\educational\controller;


use app\classes\model\ClassModel;
use app\course\model\CourseModel;
use app\educational\model\MessageModel;
use app\system\model\SchoolModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Log;

class MessageController extends AdminBaseController
{
    /**
     * 发送消息列表
     * @return mixed
     */
    public function index()
    {
        $param = $this->request->param();
        $limit = config('limit_per_page');
        $where = [
            'm.shop_id' => ['=', $this->admin_shop_id],
        ];

        //TODO(steven):权限限制
        $uid = cmf_get_current_admin_id();
        $class_mdl = new ClassModel();
        $roles = $class_mdl->roleAuth($uid, $this->admin_shop_id);
        if (count($roles) > 0) {
            foreach ($roles as $v) {
                if ($v['name'] == '教师') {
                    $where['mu.receive_uid'] = ['=', $uid];
                    break;
                }
            }
        }

        if(!empty($param['sender_name'])) {
            //发送者
            $where['u.user_login'] = ['like','%'.trim($param['sender_name']).'%'];
        }

        if(!empty($param['keywords'])) {
            //关键字
            $where['m.subject|m.content'] = ['like', '%'.trim($param['keywords']).'%'];
        }

        if(!empty($param['start']) && !empty($param['end'])) {
            //缴费时间
            $start = strtotime($param['start']);
            $end = strtotime('+23 hours 59 minutes 59 seconds', strtotime($param['end']));
            $where['m.create_time'] = [['>= time', $start], ['<= time', $end]];
        } else {
            if (!empty($param['start'])) {
                $where['m.create_time'] = ['>= time', strtotime($param['start'])];
            }
            if (!empty($param['end'])) {
                $end = strtotime('+23 hours 59 minutes 59 seconds', strtotime($param['end']));
                $where['m.create_time'] = ['<= time', $end];
            }
        }

        //分页附加参数
        $page_query = [
            'sender_name' => isset($param['sender_name']) ? $param['sender_name'] : '',
            'keywords' => isset($param['keywords']) ? $param['keywords'] : '',
            'start' => isset($param['start']) ? $param['start'] : '',
            'end' => isset($param['end']) ? $param['end'] : '',
        ];

        //获取消息列表
        $score_mdl = new MessageModel();
        $data = $score_mdl->getMessages($where,[],$limit,$page_query);

        $this->assign('param',$param);
        $this->assign('messages',$data);
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    /**
     * 我的消息
     * @return mixed
     */
    public function info()
    {
        $param = $this->request->param();
        $limit = config('limit_per_page');
        $uid = cmf_get_current_admin_id();

        $where = [
            'm.type' => ['=', 0],  //站内信
            'mu.receive_uid' => ['=', $uid],
            'm.shop_id' => ['=', $this->admin_shop_id],
        ];

        //获取消息列表
        $score_mdl = new MessageModel();
        $data = $score_mdl->getMessages($where,[],$limit,[]);

        $this->assign('param',$param);
        $this->assign('messages',$data);
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    /**
     * 我的消息详情页
     * @return mixed
     */
    public function infoDetail()
    {
        $param = $this->request->param();
        $msg_id = trim($param['msg_id']);
        if(empty($msg_id) || !is_numeric($msg_id)){
            $this->error('参数错误');
        }
        //当前用户
        $uid = cmf_get_current_admin_id();

        //获取消息
        $where = [
            'm.id' => $msg_id,
            'm.shop_id' => $this->admin_shop_id,
            'mu.receive_uid' => $uid,
        ];
        $msg = Db::name('message_user')->alias('mu')
            ->field('m.*,mu.msg_status')
            ->join('message m', 'm.id=mu.msg_id')
            ->where($where)
            ->find();

        if(count($msg) <= 0){
            $this->error('没有该信息或信息已删除');
        }else{
            //修改信息已读
            $condition = [
                'msg_id' => $msg_id,
                'receive_uid' => $uid,
            ];
            Db::name('message_user')->where($condition)->update(['msg_status' => 1]);
        }

        $this->assign('message',$msg);
        return $this->fetch();
    }

    /**
     * 已读消息修改状态
     * @return \think\response\Json
     */
    public function ajaxRead()
    {
        if($this->request->isPost()){
            $param = $this->request->post();
            if(empty($param['msg_id'])){
                $json_data = [
                    'code' => 0,
                    'msg' => '参数有误',
                    'data' => []
                ];
                return json($json_data);
            }
            //当前用户
            $uid = cmf_get_current_admin_id();
            //修改已读
            $condition = [
                'msg_id' => trim($param['msg_id']),
                'receive_uid' => $uid,
            ];
            Db::name('message_user')->where($condition)->update(['msg_status' => 1]);

            //获取消息内容
            $content = Db::name('message')->where(['id' => trim($param['msg_id'])])->value('content');

            $json_data = [
                'code' => 1,
                'msg' => 'success',
                'data' => $content
            ];
            return json($json_data);

        }else{
            $json_data = [
                'code' => 0,
                'msg' => '请求错误',
                'data' => []
            ];
            return json($json_data);
        }
    }

    /**
     * 给家长发送通知主页
     * @return mixed
     */
    public function sendToParents()
    {
        //获取校区
        $school_mdl = new SchoolModel();
        $schools = $school_mdl->getAllSchool($this->admin_shop_id);
        //获取课程
        $course_mdl = new CourseModel();
        $courses = $course_mdl->getAllCourse($this->admin_shop_id);

        $this->assign('school',$schools);
        $this->assign('course',$courses);
        return $this->fetch();
    }

    /**
     * @return \think\response\Json
     */
    public function ajax_class()
    {
        if($this->request->isPost()){
            $param = $this->request->post();

            if(empty($param['school_id'])){
                $json_data = [
                    'code' => 0,
                    'msg' => '校区不能为空',
                    'data' => []
                ];
                return json($json_data);
            }

            //获取班级
            $where = [
                'shop_id' => ['eq', $this->admin_shop_id],
                'school_id' => ['eq', $param['school_id']],
            ];
            $class_mdl = new ClassModel();
            $data = $class_mdl->getClassByField($where);

            if(count($data) < 0){
                $json_data = [
                    'code' => 0,
                    'msg' => '没有更多数据',
                    'school_id' => $param['school_id'],
                    'data' => $data
                ];
                return json($json_data);
            }

            $json_data = [
                'code' => 1,
                'msg' => 'success',
                'school_id' => $param['school_id'],
                'data' => $data
            ];
            return json($json_data);
        }
    }

    /**
     * 获取家长
     * @return \think\response\Json
     */
    public function ajaxParent()
    {
        if($this->request->isPost()){
            $param = $this->request->post();

//            if(empty($param['school_id'])){
//                $json_data = [
//                    'code' => 0,
//                    'msg' => '学校不能为空',
//                    'data' => []
//                ];
//                return json($json_data);
//            }

            //获取家长
            $data = $this->getParents($param['school_id'],$param['class_id'],$param['course_id']);

            if(count($data) < 0){
                $json_data = [
                    'code' => 0,
                    'msg' => '没有更多数据',
                    'school_id' => $param['school_id'],
                    'data' => $data
                ];
                return json($json_data);
            }

            $json_data = [
                'code' => 1,
                'msg' => 'success',
                'school_id' => $param['school_id'],
                'data' => $data
            ];
            return json($json_data);
        }
    }

    /**
     * @param $school_id
     * @param $class_id
     * @param $course_id
     * @return array
     */
    public function getParents($school_id=0, $class_id=0, $course_id=0)
    {
        $result = [];
//        if(empty($school_id) || !is_numeric($school_id)){
//            return $result;
//        }

        $condition = [
            'c.shop_id' => ['eq', $this->admin_shop_id],
            'c.delete_time' => ['eq', 0],
        ];

        if(!empty($school_id) && is_numeric($school_id)){
            $condition['c.school_id'] = ['eq', $school_id];
        }

        if(!empty($class_id) && is_numeric($class_id)){
            $condition['c.id'] = ['eq', $class_id];
        }

        if(!empty($course_id) && is_numeric($course_id)){
            $condition['c.course_id'] = ['eq', $course_id];
        }

        $class_mdl = new ClassModel();
        $data = $class_mdl->alias('c')
            ->distinct(true)
            ->field('u.id,u.realname,u.user_email')
            ->join('class_student cs','c.id=cs.class_id')
            ->join('student t','t.id=cs.student_id')
            ->join('user u','t.u_id=u.id')
            ->where($condition)
            ->select();

        $total = count($data);
        if($total > 0){
            $data->toArray();
        }

        $result['total'] = $total;
        $result['res'] = $data;

        return $result;
    }

    /**
     *发送信息
     */
    public function sendPost()
    {
        $msg = '';
        $cur_time = time();
        $validate = validate('Message');
        if($this->request->isPost()){
            $data = $this->request->except('send_school_id,send_class_id,send_course_id');
            if(!$validate->check($data)){
                $this->error($validate->getError());
            }
            $send_uid = cmf_get_current_admin_id();

            //消息类型
            $type = $data['type'];
            if($type == 0 || $type == 2){
                //站内信息
                if(empty($data['subject'])){
                    $this->error('主题不能为空');
                }
            }else{
                //TODO(Steven):短信
                $this->error('暂且没有短信平台');
            }

            //校区
            $school_id = $this->request->post('send_school_id');
//            if(empty($school_id) || !is_numeric($school_id)){
//                $this->error('学校不能为空','message/index');
//            }
            //班级
            $class_id = $this->request->post('send_class_id');
            //课程
            $course_id = $this->request->post('send_course_id');
            //获取家长
            $result = $this->getParents($school_id, $class_id, $course_id);

            $data['shop_id'] = $this->admin_shop_id;
            $data['send_uid'] = $send_uid;
            $data['create_time'] = $cur_time;

            //发送消息
            $msg_mdl = new MessageModel();
            if($type == 0){
                //站内信息
                $res = $msg_mdl->sendMsg($data, $result['res']);
            }elseif ($type == 2){
                //邮件
                $email = array_column($result['res']->toArray(),'user_email');
                $res = $msg_mdl->sendEmail($data, $email, $msg);
            }else{
                //短信
                $res = true;
            }
            if($res){
                $this->success('发送成功');
            }else{
                //记录日志
                $email = str_replace('SMTP 错误：收件人地址错误：','',$msg);
                $content = lang('MAIL_SEND_FAILED',['email'=>$email]);
                do_log($content,$msg_mdl->getLastInsID(),'message,message_user');

                $this->success('发送成功');
                //$this->error($msg);
            }
        }
    }
}